<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

function competitors_list_page()
{
    @$output = drupal_render(drupal_get_form('competitors_list_form'));
    return $output;
}

function competitors_list_form($form, &$form_state)
{
//    $form['address'] = _insert_address_selection_form($form, $form_state, 'address', 1, FALSE, '');
    _insert_fertilizer_selection_search_form($form,$form_state['values']['fertilizer']);
    _insert_brand_selection_form($form,$form_state['values']['brand']);
    $init_year =  !empty($form_state['values']['year'])?$form_state['values']['year']:"";
    $init_month =  !empty($form_state['values']['_month'])?$form_state['values']['_month']:"";
    _insert_date_selection_form($form,$form_state,5,$init_year,$init_month,TRUE);
    $fields = array(
        '' => '请选择',
        'factory_price' => '出厂价格',
        'arrival_price' => '到站价格',
        'retail_price' => '零售价格',
        'rebate' => '返利'
    );
    numerical_range_search($form,$fields);
    $table['#markup'] = data_list_view_page($form, $form_state);
    ajax_submit_form($form,$form_state,$table,'');

    return $form;
}


function competitors_list_form_validate($form, &$form_state)
{

}

function data_list_view_page($form = '', &$form_state = '')
{
        global $user;
        $output = '';
        //表头
        $header = array(
            array('data' => '选择', 'class' => ['essential no']),
            array('data' => '地址', 'class' => ['essential province']),
            array('data' => '日期', 'class' => ['integrant essential break date'], 'field' => 'date'),
            array('data' => '肥料类别', 'class' => ['essential fertilizer']),
            array('data' => '化肥品牌', 'class' => ['essential brand']),
            array('data' => 'S/M', 'class' => ['essential brand']),
            array('data' => 'N', 'class' => ['essential brand']),
            array('data' => 'P', 'class' => ['essential brand']),
            array('data' => 'K', 'class' => ['essential brand']),
            array('data' => '总含量', 'class' => ['essential brand']),
            array('data' => '出厂价格', 'class' => ['integrant essential break factory_price'], 'field' => 'factory_price'),
            array('data' => '到站价格', 'class' => ['essential break arrival_price'], 'field' => 'arrival_price'),
            array('data' => '零售价格', 'class' => ['essential break retail_price'], 'field' => 'retail_price'),
            array('data' => '返利', 'class' => ['essential break rebate'], 'field' => 'rebate'),
            array('data' => '业务员', 'class' => ['essential break rebate']),
            array('data' => '操作', 'class' => ['essential more']),
            array('data' => '克隆', 'class' => ['essential more']),
        );
        $query = db_select('addr', 'A')->extend('PagerDefault')->extend('TableSort');//地址表
        $query->join('competitors', 'C', 'A.addr_id=C.addr_id');//内连接 成一个表
        $query->leftJoin('fertilizer', 'F', 'F.fertilizer_id=C.fertilizer_id');
        $query->leftJoin('brand', 'B', 'B.brand_id=C.brand_id');
        $query->fields('C', array('competitors_id', 'date', 'factory_price', 'arrival_price', 'retail_price', 'rebate', 'author_uid','n','p','k','npk_total','sm'));
        $query->addField('F', 'fertilizer_name');
        $query->addField('B', 'brand_name');
        $query->join('employee','E','C.author_uid = E.employee_id');
        $query->addField('E', 'employee_name');
        //地址级别查询
        if (!empty($form_state['values']['province'])) {//省级
            $query->condition('A.province_id', $form_state['values']['province'], '=');
        }
        //模糊条件筛选
        if (!empty($form_state['values']['year'])) {//模糊年度查询条件
            $query->condition('C.date', db_like($form_state['values']['year']) . '-' . '%', 'LIKE');
        }
        if (!empty($form_state['values']['month'])) {//模糊年度查询条件
            if($form_state['values']['month']<10){
                $like = '%-0'.db_like($form_state['values']['month']) . '-' . '%';
            }else{
                $like = '%-'.db_like($form_state['values']['month']) . '-' . '%';
            }
            $query->condition('C.date',$like , 'LIKE');
        }

        if(!empty($form_state['values']['fertilizer'])){
            $query->condition('C.fertilizer_id', $form_state['values']['fertilizer'], '=');
        }
        if(!empty($form_state['values']['brand'])){
            $query->condition('C.brand_id', $form_state['values']['brand'], '=');
        }
        if(!user_access('view all competitors') && user_access('view own competitors')){
            $query->condition('C.author_uid',$user->uid, '=');
        }
        $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
        $query->addField('A1', 'name', 'province');
        if(!empty($form_state['values']['field'])){
            if(!empty($form_state['values']['min_number']) && !empty($form_state['values']['max_number'])){
                $db_and = db_and();
                $db_and->condition('C.'.$form_state['values']['field'], $form_state['values']['min_number'], '>');
                $db_and->condition('C.'.$form_state['values']['field'], $form_state['values']['max_number'], '<');
                $query->condition($db_and);
            }elseif(!empty($form_state['values']['min_number'])){
                $query->condition('C.'.$form_state['values']['field'], $form_state['values']['min_number'], '>');
            }elseif(!empty($form_state['values']['max_number'])){
                $query->condition('C.'.$form_state['values']['field'], $form_state['values']['max_number'], '<');
            }
        }
        if(empty($form_state['values']) || empty($form_state['values']['order'])) {
            $query->orderBy('C.timestamp', 'DESC');
        }
        $query->limit(variable_get("list_page_item_number", 5));
        $competitorsInfo = $query->orderByHeader($header)->execute();

        $rows = array();
        //表内容
        $n = 1;
        foreach ($competitorsInfo as $row) {
            if (nonghua_user_access('competitors', 'delete', $row->competitors_id, $row->author_uid, 0)) {
                $disabled = ' class="listViewTableCheck" ';
            } else{
                $disabled = ' disabled="true" ';
            }
            $rows[] = array(
                array('data' => '<input type="checkbox"'.$disabled.' value ="' . $row->competitors_id . '"/>' . $n++, 'class' => ['integrant essential no']),

                array('data' => $row->province, 'class' => ['integrant essential province']),
                array('data' => substr($row->date, 0, 7), 'class' => ['integrant goRight essential break date']),
                array('data' => $row->fertilizer_name, 'class' => ['integrant haveTobr goRight essential fertilizer']),
                array('data' => $row->brand_name, 'class' => ['integrant goRight essential brand']),
                array('data' => $row->sm, 'class' => ['integrant goRight essential sm']),
                array('data' => $row->n, 'class' => ['integrant goRight essential n']),
                array('data' => $row->p, 'class' => ['integrant goRight essential p']),
                array('data' => $row->k, 'class' => ['integrant goRight essential k']),
                array('data' => $row->npk_total, 'class' => ['integrant goRight essential npk_total']),
                array('data' => $row->factory_price, 'class' => ['integrant essential break factory_price']),
                array('data' => $row->arrival_price, 'class' => ['essential break arrival_price']),
                array('data' => $row->retail_price, 'class' => ['essential break retail_price']),
                array('data' => $row->rebate, 'class' => ['essential break rebate']),
                array('data' => $row->employee_name, 'class' => ['essential break rebate']),
                array('data' => '<a href="'.base_path().'competitors/edit/' . $row->competitors_id . '" data-toggle="modal" target = "_top"><img width="20px" height="20px" src="'.base_path().'sites/all/themes/tweme/images/images/cz.png"/></a>', 'class' => 'essential more'),
                array('data' => '<a href="'.base_path().'competitors/clone/' . $row->competitors_id . '" data-toggle="modal"class="btn" target = "_top">克隆</a>', 'class' => ['essential']),
            );
        }
        $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('没有记录'), 'attributes' => array('class' => array('table table-bordered table-striped table-hover enhanced')))); //表格
        /*	 * *按钮** */
        if(sizeof($rows) > 0 && (user_access('delete own competitors') ||  user_access('delete all competitors'))) {
            $output .= '<a href="javascript:void(0)" id="listViewTableSelectAll" data-toggle="modal" class="btn btn-mini">全选</a>';
            $output .= '<a href="javascript:void(0)" id="listViewTableDeleteSelected" data-toggle="modal" class="btn btn-mini">删除所选</a>';
        }
    $output .= '<a href="'.base_path().'competitors/export?fertilizer=' .$form_state['values']['fertilizer'].'&brand='.$form_state['values']['brand'].'&year='.$form_state['values']['year'].'&month='.$form_state['values']['month'].'&field='.$form_state['values']['field'].'&min_number='.$form_state['values']['min_number'].'&max_number='.$form_state['values']['max_number'].'" data-toggle="modal" class="btn btn-mini">导出</a>';
    $output .= theme('pager');
        return $output;
}

include_once 'competitors.edit.page.inc';

function competitors_delete()
{
    ajax_table_delete('competitors', 'competitors_id');
}

function competitors_export($form,&$form_state){
    $letter = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O');
    $tableheader = array('地址','肥料类别','化肥品牌','日期','S/M','N', 'P', 'K', '总含量','出厂价格','到站价格','零售价格','返利','业务员');
    $data = get_competiters_data($form, $form_state);
    nonghua_php_excel($letter,$tableheader,$data,'竞品价格数据');
}

function get_competiters_data($form = '', &$form_state = ''){
    global $user;
    $query = db_select('addr', 'A');
    $query->join('competitors', 'C', 'A.addr_id=C.addr_id');//内连接 成一个表
    $query->leftJoin('fertilizer', 'F', 'F.fertilizer_id=C.fertilizer_id');
    $query->leftJoin('brand', 'B', 'B.brand_id=C.brand_id');
    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->addField('A1', 'name', 'province');
    $query->addField('F', 'fertilizer_name');
    $query->addField('B', 'brand_name');
    $query->fields('C', array( 'date','sm','n','p','k','npk_total', 'factory_price', 'arrival_price', 'retail_price', 'rebate'));

    $query->join('employee','E','C.author_uid = E.employee_id');
    $query->addField('E', 'employee_name');
    //地址级别查询
    if (!empty($_GET['province'])) {//省级
        $query->condition('A.province_id', $form_state['values']['province'], '=');
    }
    //模糊条件筛选
    if (!empty($_GET['year'])) {//模糊年度查询条件
        $query->condition('C.date', db_like($_GET['year']) . '-' . '%', 'LIKE');
    }
    if (!empty($_GET['month'])) {//模糊年度查询条件
        if($_GET['month']<10){
            $like = '%-0'.db_like($_GET['month']) . '-' . '%';
        }else{
            $like = '%-'.db_like($_GET['month']) . '-' . '%';
        }
        $query->condition('C.date',$like , 'LIKE');
    }

    if(!empty($_GET['fertilizer'])){
        $query->condition('C.fertilizer_id', $_GET['fertilizer'], '=');
    }
    if(!empty($_GET['brand'])){
        $query->condition('C.brand_id',$_GET['brand'], '=');
    }
    if(!user_access('view all competitors') && user_access('view own competitors')){
        $query->condition('C.author_uid',$user->uid, '=');
    }
    if(!empty($_GET['field'])){
        if(!empty($_GET['min_number']) && !empty($_GET['max_number'])){
            $db_and = db_and();
            $db_and->condition('C.'.$_GET['field'], $_GET['min_number'], '>');
            $db_and->condition('C.'.$_GET['field'], $_GET['max_number'], '<');
            $query->condition($db_and);
        }elseif(!empty($_GET['min_number'])){
            $query->condition('C.'.$_GET['field'], $_GET['min_number'], '>');
        }elseif(!empty($_GET['max_number'])){
            $query->condition('C.'.$_GET['field'], $_GET['max_number'], '<');
        }
    }
    $competitorsInfo = $query->execute()->fetchAll();
    return $competitorsInfo;
}